import React, { useEffect } from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { Spin, Result } from 'antd';
import { useAppSelector, useAppDispatch } from '../store';
import { selectIsAuthenticated, selectPermissionManager, selectAuthLoading, validateToken } from '../store/slices/authSlice';

interface ProtectedRouteProps {
  children: React.ReactNode;
  permissions?: string[];
  requireAll?: boolean; // 是否需要所有权限，默认false（只需要其中一个）
}

const ProtectedRoute: React.FC<ProtectedRouteProps> = ({
  children,
  permissions = [],
  requireAll = false
}) => {
  const dispatch = useAppDispatch();
  const location = useLocation();

  const isAuthenticated = useAppSelector(selectIsAuthenticated);
  const permissionManager = useAppSelector(selectPermissionManager);
  const loading = useAppSelector(selectAuthLoading);

  // 验证token有效性
  useEffect(() => {
    if (isAuthenticated && !permissionManager) {
      dispatch(validateToken());
    }
  }, [dispatch, isAuthenticated, permissionManager]);

  // 如果正在加载，显示加载状态
  if (loading) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh'
      }}>
        <Spin size="large" tip="验证中..." />
      </div>
    );
  }

  // 如果未认证，重定向到登录页
  if (!isAuthenticated) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  // 如果需要权限验证
  if (permissions && permissions.length > 0 && permissionManager) {
    const hasPermission = requireAll
      ? permissionManager.hasAllPermissions(permissions)
      : permissionManager.hasAnyPermission(permissions);

    if (!hasPermission) {
      return (
        <Result
          status="403"
          title="403"
          subTitle="抱歉，您没有权限访问此页面。"
          extra={
            <div>
              <p>需要以下权限之一：</p>
              <ul>
                {permissions.map(permission => (
                  <li key={permission}>{permission}</li>
                ))}
              </ul>
            </div>
          }
        />
      );
    }
  }

  return <>{children}</>;
};

export default ProtectedRoute;
